package com.ldk.framework.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.push.JPushDispatcher;
import com.ldk.framework.push.PushTargetApp;
import com.ldk.framework.push.PushCustomMsg;
import com.ldk.framework.service.IPushMessageService;
import com.ldk.framework.dao.IPushMessageDAO;
import com.ldk.framework.entity.PushMessage;

/**
* PushMessageService接口实现类
* @author xiangwl
*/
@Service
public class PushMessageService extends BaseService<PushMessage> implements IPushMessageService {

	@Autowired
	private IPushMessageDAO pushMessageDAO;

	@Override
	protected IBaseDAO<PushMessage> getBaseDao() {
     	return this.pushMessageDAO;
	}
	@Override
	public Boolean pushToUser(String dbKey, PushMessage message, PushTargetApp targetApp,
			PushCustomMsg customMsg, List<String> aliasList, final Boolean saveToDb) {
		if(message == null)
			return false;
		if(StringUtils.isEmpty(message.getToUser())){
			logger.error("推送指定用户为空");
			return false;
		}
		if(StringUtils.isEmpty(message.getTitle())){
			logger.error("推送标题为空");
			return false;
		}
		if(StringUtils.isEmpty(message.getMessage())){
			logger.error("推送内容为空");
			return false;
		}
		if(aliasList == null || aliasList.isEmpty()){
			logger.error("推送指定别名列表为空");
			return false;
		}
		if(customMsg == null){
			logger.error("推送自定义消息为null");
			return false;
		}
		Map<String, String> extras = customMsg.toMap();
		
		Boolean pushed = JPushDispatcher.getInstance().pushWithAliasAndSound(targetApp.getName(), message.getTitle(), message.getMessage(), customMsg.getSound(), extras, aliasList);
		logger.error("pushed="+pushed+",message="+customMsg.toJson()+",aliasList="+ JSONObject.toJSONString(aliasList));
		if(pushed && saveToDb){
			try{
				for (String toUser : aliasList) {
					message.setToUser(toUser);
					insert(dbKey, message);
				}
			}
			catch(Exception e){
				logger.error("PushMessageService.pushToUser");
			}
		}
		return pushed;
	}
}
